package cn.yymc.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class TestZuulFilter2 extends ZuulFilter {

    /**
     * 当前过滤器的类型
     * @return
     */
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    /**
     * 指定过滤器的执行顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER-3 ; //5  数值越小，优先级越高
    }

    /**
     * 过滤器是否启用
     * @return  false为关闭此过滤器 true 为开启此过滤器
     */
    @Override
    public boolean shouldFilter() {
        return false;
    }

    /**
     * 具体的业务逻辑代码
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        System.out.println("prefix过滤器22222222222222222222执行~~~");

        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getParameter("token");

        if(StringUtils.isEmpty(token)|| !"123".equals(token)){

            System.out.println("信息错误，不允许访问！"+token);

            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);

        }

        return null;//返回的没有什么实质意义
    }
}
